package com.buddy.qreport.datasource.dynamic;

import com.buddy.qreport.datasource.entity.DataSourceEntity;
import com.buddy.qreport.datasource.service.IDataSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.List;
@Slf4j
@Configuration
public class DynamicDataSourceConfig implements ApplicationRunner {


    @Autowired
    private DynamicDataSource dynamicDataSource;


    @Autowired
    @Qualifier("QREPORT_DataSourceService")
    private IDataSourceService dataSourceService;


    /**
     * springboot启动后从数据库加载动态数据源
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {

        if(dynamicDataSource == null){

            log.info("未加载动态数据源");
            return;
        }

        log.info("开始加载动态数据源");



        List<DataSourceEntity> list = dataSourceService.getList();



        for(DataSourceEntity ds : list){

            DataSource dataSource = dataSourceService.cast(ds);

            if(dataSource != null){

                log.info("添加数据源id={}",ds.getDatasourceId());


                dynamicDataSource.addDataSource(ds.getDatasourceId(),dataSource);
            }

        }


        log.info("动态数据源加载完毕");

    }
}
